/**
 * 显示消息提示框
 * @param content 提示的标题
 */
export function toast(content) {
	uni.showToast({
		icon: 'none',
		title: content
	})
}

/**
 * 显示模态弹窗
 * @param content 提示的标题
 */
export function showConfirm(content) {
	return new Promise((resolve, reject) => {
		uni.showModal({
			title: '提示',
			content: content,
			cancelText: '取消',
			confirmText: '确定',
			success: function(res) {
				resolve(res)
			}
		})
	})
}

/**
 * 参数处理
 * @param params 参数
 */
export function tansParams(params) {
	let result = ''
	for (const propName of Object.keys(params)) {
		const value = params[propName]
		var part = encodeURIComponent(propName) + "="
		if (value !== null && value !== "" && typeof(value) !== "undefined") {
			if (typeof value === 'object') {
				for (const key of Object.keys(value)) {
					if (value[key] !== null && value[key] !== "" && typeof(value[key]) !== 'undefined') {
						let params = propName + '[' + key + ']'
						var subPart = encodeURIComponent(params) + "="
						result += subPart + encodeURIComponent(value[key]) + "&"
					}
				}
			} else {
				result += part + encodeURIComponent(value) + "&"
			}
		}
	}
	return result
}

/**
 * @param {Object} date
 * 以yyyy-mm-dd格式返回当前时间
 */
export function formatDate() {
	let date = new Date()
	const year = date.getFullYear();
	const month = String(date.getMonth() + 1).padStart(2, '0');
	const day = String(date.getDate()).padStart(2, '0');
	return `${year}-${month}-${day}`;
}

/**
 * @param {Object} elementSelector
 * @param {Object} callback
 * 计算当前元素距离页面底部距离
 */
export function getDistanceToBottom(elementSelector, callback) {
	uni.createSelectorQuery()
		.select(elementSelector)
		.boundingClientRect(rect => {
			uni.getSystemInfo({
				success: res => {
					const distanceToBottom = res.windowHeight - rect.bottom;
					callback(distanceToBottom);
				}
			});
		})
		.exec();
}

/**
 * @param {Object} params
 * 时间转换
 */
export function dateChange(params) {
	let date = new Date(params);
	let year = date.getFullYear();
	let month = String(date.getMonth() + 1).padStart(2, '0');
	let day = String(date.getDate()).padStart(2, '0');
	let hours = String(date.getHours()).padStart(2, '0');
	let minutes = String(date.getMinutes()).padStart(2, '0');
	let seconds = String(date.getSeconds()).padStart(2, '0');

	let formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
	return formattedDate
}

// 助手函数：将参数添加到URL中
function addParamsToUrl(url, params) {
	if (Object.keys(params).length === 0) {
		return url;
	}
	const paramStr = Object.keys(params)
		.map((key) => `${key}=${encodeURIComponent(params[key])}`)
		.join("&");
	return `${url}?${paramStr}`;
}

// 封装路由跳转方法
export function toPath(url, params = {}) {
	uni.navigateTo({
		url: addParamsToUrl(url, params),
		// animationType: 'zoom-out',
		animationDuration: 200
	});
}